package download

import (
	"fmt"
	"os"
	"path/filepath"
	"time"
)

func DownloadRemoteFile(urlPath, savePath string, timeout time.Duration, useResume bool) (time.Duration, int64, error) {
	// 将根路径进行加工，例如\转为/
	downloadUrl := filepath.ToSlash(urlPath)
	localFilePath := filepath.FromSlash(savePath)

	startTime := time.Now()

	// 创建本地目录
	localDir := filepath.Dir(localFilePath)
	if err := os.MkdirAll(localDir, os.ModePerm); err != nil {
		return 0, 0, fmt.Errorf("创建目录失败: %v", err)
	}

	var fileSize int64

	// 判断是否使用断点续传，如果不使用，则直接下载
	if !useResume {
		if fileSize, err := directDownloadFile(downloadUrl, localFilePath, timeout); err != nil {
			return 0, fileSize, fmt.Errorf("下载文件失败: %v", err)
		}
		return time.Since(startTime), fileSize, nil
	}

	// 获取文件大小
	fileSize, fileLastModTime, err := getRemoteFileMetadata(downloadUrl)
	if err != nil {
		return 0, fileSize, fmt.Errorf("获取文件大小失败: %v", err)
	}
	fileSize, err = resumeDownloadFile(downloadUrl, localFilePath, fileSize, fileLastModTime)
	if err != nil {
		return 0, fileSize, fmt.Errorf("下载文件失败: %v", err)
	}
	// 大文件下载
	return time.Since(startTime), fileSize, nil
}
